package com.csxh.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csxh.web.util.WebUtil;


public class CheckLoginFilter implements Filter {

	private String[] checkJspPages;
	private String loginJspPage;

	public void destroy() {

	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		
		if(this.checkJspPages!=null && this.checkJspPages.length>0 ){
		
			// 获取uri地址
			HttpServletRequest request = (HttpServletRequest) servletRequest;
			String uri = request.getServletPath();//xxx.jsp
			for(String checkJspPage : this.checkJspPages){
				if(uri.endsWith(checkJspPage)){
					
					if(!WebUtil.checkLogin(request)){
						HttpServletResponse respons=(HttpServletResponse)servletResponse;
						String path=this.loginJspPage;
						if(!path.startsWith("/")){
							path="/"+path;
						}
						//加上应用的上下文
						path=request.getServletContext().getContextPath()+path+"?redirectPage="+checkJspPage;
						respons.sendRedirect(path);
						return;
					}
				}
			}
		}
		filterChain.doFilter(servletRequest, servletResponse);

		
		
	}
	
	public void init(FilterConfig config) throws ServletException {
         String checkJspPages=config.getInitParameter("checkJspPages");
         //Pattern.compile("[,\\s+]+").matcher(checkJspPages);
         this.checkJspPages=checkJspPages.split("[,\\s+]+");
         this.loginJspPage=config.getInitParameter("loginJspPage");
         
         this.loginJspPage=null!=this.loginJspPage ? this.loginJspPage : "/login.jsp";
         
   }

}